import { reqGetUserInfo, reqGetUserInfoById, reqLogin } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    setToken(state, newToken) {
      state.token = newToken
      setToken(newToken)
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    removeToken(state) {
      state.token = ''
      removeToken()
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }

  },
  actions: {
    // async login(context, data) {
    //   const res = await reqLogin(data)
    //   const newToken = res.data.data
    //   setToken(newToken)
    //   console.log(res)
    //   context.commit('setToken', newToken)
    // }
    login(context, data) {
      return new Promise((resolve, reject) => {
        reqLogin(data).then(res => {
          const newToken = res.data
          console.log(newToken)
          context.commit('setToken', newToken)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    async getUserInfo(context) {
      const { data: data1 } = await reqGetUserInfo()
      // console.log(data)
      const { data: data2 } = await reqGetUserInfoById(data1.userId)
      const userInfo = {
        ...data1, ...data2
      }
      context.commit('setUserInfo', userInfo)
      // context.commit
      return userInfo
    },
    logOut(context) {
      context.commit('removeToken')
      context.commit('removeUserInfo')
    }
  }
}

